// src/stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref(null)
  const accessToken = ref(localStorage.getItem('access_token') || '')
  const refreshToken = ref(localStorage.getItem('refresh_token') || '')
  const tokenExpiry = ref(localStorage.getItem('token_expiry') || '')

  // 计算属性
  const isAuthenticated = computed(() => {
    return !!accessToken.value && !!user.value && !isTokenExpired.value
  })

  const isTokenExpired = computed(() => {
    if (!tokenExpiry.value) return true
    return Date.now() >= parseInt(tokenExpiry.value)
  })

  const userType = computed(() => {
    return user.value?.user_type || null
  })

  // 检查用户是否已完善信息 - 修正逻辑
  const isProfileCompleted = computed(() => {
    if (!user.value) return false
    
    const type = user.value.user_type
    
    // 根据用户类型检查是否已完善信息
    switch (type) {
      case 'student':
        return !!(user.value.student_info && user.value.student_info.id)
      case 'teacher':
        return !!(user.value.teacher_info && user.value.teacher_info.id)
      case 'admin':
        return true // 管理员默认已完善信息
      default:
        return false
    }
  })

  const userAvatar = computed(() => {
    return user.value?.avatar || '/default-avatar.png'
  })

  const userDisplayName = computed(() => {
    if (!user.value) return ''
    
    // 优先显示真实姓名，其次是用户名
    if (user.value.student_info?.name) {
      return user.value.student_info.name
    }
    if (user.value.teacher_info?.name) {
      return user.value.teacher_info.name
    }
    if (user.value.agent_info?.name) {
      return user.value.agent_info.name
    }
    
    return user.value.username || '用户'
  })

  // API 基础配置
  const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000'

  // 设置token
  const setTokens = ({ accessToken: newAccessToken, refreshToken: newRefreshToken, expiresIn }) => {
    accessToken.value = newAccessToken
    refreshToken.value = newRefreshToken
    
    // 计算过期时间
    const expiry = Date.now() + (expiresIn * 1000)
    tokenExpiry.value = expiry.toString()
    
    // 存储到localStorage
    localStorage.setItem('access_token', newAccessToken)
    localStorage.setItem('refresh_token', newRefreshToken)
    localStorage.setItem('token_expiry', expiry.toString())
  }

  // 设置用户信息
  const setUser = (userData) => {
    user.value = userData
    localStorage.setItem('user_info', JSON.stringify(userData))
    console.log('用户信息已设置:', {
      username: userData.username,
      userType: userData.user_type,
      isProfileCompleted: isProfileCompleted.value
    })
  }

  // 更新用户信息
  const updateUser = (updatedData) => {
    if (user.value) {
      user.value = { ...user.value, ...updatedData }
      localStorage.setItem('user_info', JSON.stringify(user.value))
    }
  }

  // 标记信息完善状态
  const markProfileCompleted = (profileData) => {
    if (user.value) {
      const type = user.value.user_type
      
      if (type === 'student') {
        user.value.student_info = profileData
      } else if (type === 'teacher') {
        user.value.teacher_info = profileData
      }
      
      localStorage.setItem('user_info', JSON.stringify(user.value))
    }
  }

  // 获取当前用户的详细信息
  const fetchUserProfile = async () => {
    if (!accessToken.value) {
      throw new Error('No access token available')
    }

    try {
      const response = await fetch(`${API_BASE_URL}/auth/me`, {
        headers: {
          'Authorization': `Bearer ${accessToken.value}`,
          'Content-Type': 'application/json',
        }
      })

      if (!response.ok) {
        if (response.status === 401) {
          // Token 可能已过期，尝试刷新
          await refreshAccessToken()
          return await fetchUserProfile() // 重新获取
        }
        throw new Error('Failed to fetch user profile')
      }

      const userData = await response.json()
      setUser(userData)
      
      return userData
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 刷新token
  const refreshAccessToken = async () => {
    if (!refreshToken.value) {
      throw new Error('No refresh token available')
    }

    try {
      const response = await fetch(`${API_BASE_URL}/auth/refresh`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          refresh_token: refreshToken.value
        })
      })

      if (!response.ok) {
        throw new Error('Token refresh failed')
      }

      const data = await response.json()
      
      setTokens({
        accessToken: data.access_token,
        refreshToken: data.refresh_token,
        expiresIn: data.expires_in
      })

      if (data.user_info) {
        setUser(data.user_info)
      }

      return data.access_token
    } catch (error) {
      console.error('Token refresh error:', error)
      clearAuth()
      throw error
    }
  }

  // 清除认证信息
  const clearAuth = () => {
    user.value = null
    accessToken.value = ''
    refreshToken.value = ''
    tokenExpiry.value = ''
    
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('token_expiry')
    localStorage.removeItem('user_info')
    localStorage.removeItem('remember-user')
    
    sessionStorage.clear()
  }

  // 登出
  const logout = async () => {
    try {
      if (accessToken.value) {
        await fetch(`${API_BASE_URL}/auth/logout`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${accessToken.value}`,
            'Content-Type': 'application/json',
          }
        })
      }
    } catch (error) {
      console.error('登出API调用失败:', error)
    } finally {
      clearAuth()
    }
  }

  // 初始化
  const init = () => {
    const savedUser = localStorage.getItem('user_info')
    if (savedUser) {
      try {
        user.value = JSON.parse(savedUser)
      } catch (error) {
        console.error('Failed to parse saved user info:', error)
        localStorage.removeItem('user_info')
      }
    }
  }

  // 检查是否需要完善信息
  const needsProfileCompletion = () => {
    return isAuthenticated.value && !isProfileCompleted.value && 
           (userType.value=== 'student' || userType.value === 'teacher')
  }

  // 获取完善信息的路由路径
  const getProfileCompletionRoute = () => {
    const type = userType.value
    if (type === 'student') {
      return '/complete-profile/student'
    } else if (type === 'teacher') {
      return '/complete-profile/teacher'
    }
    return null
  }

  // 获取用户主页路径
  const getUserDashboardRoute = () => {
    const type = userType.value
    if (type === 'student') {
      return '/student/dashboard'
    } else if (type === 'teacher') {
      return '/teacher/dashboard'
    } else if (type === 'admin') {
      return '/admin/dashboard'
    }
    return '/'
  }

  return {
    // 状态
    user,
    accessToken,
    refreshToken,
    
    // 计算属性
    isAuthenticated,
    isTokenExpired,
    userType,
    isProfileCompleted,
    userAvatar,
    userDisplayName,
    
    // 方法
    setTokens,
    setUser,
    updateUser,
    markProfileCompleted,
    clearAuth,
    refreshAccessToken,
    fetchUserProfile,
    init,
    logout,
    needsProfileCompletion,
    getProfileCompletionRoute,
    getUserDashboardRoute
  }
})